# coding: utf8

#########################################################################
## This is a samples controller
## - index is the default action of any application
## - user is required for authentication and authorization
## - download is for downloading files uploaded in the db (does streaming)
## - call exposes all registered services (none by default)
#########################################################################  
valid_cron_ip = "0.1.0.1"

def remove_old_notes():
    if request.env.remote_addr != valid_cron_ip:
        return False
    from datetime import datetime
    from datetime import timedelta
    old = db(db.note.removal_date < datetime.now()).delete()
    db.commit()
    return True

@auth.requires_login()
def index():
    notes = db(db.note.user_id==auth.user.id).select(db.note.ALL)
    if session._flash:
        response.flash = session._flash
        session._flash = None
    else:
        response.flash = T('Welcome to my sticky notes')

    return dict(notes=notes)


@auth.requires_login()
def create():
    form = crud.create(db.note)
    if form.accepts(request.vars,session):
        session._flash = T('The sticky note was succesfully created')
        form = None
    return dict(form=form)


@auth.requires_login()
def update():
    note = None
    note_id = None

    try:
        note = db(db.note.id==request.args[0]).select()
    except IndexError:
        note = db(db.note.id==0).select()

    if len(note):
        if note[0].user_id == auth.user.id:
            note_id = note[0].id
    else:
        note_id = 0

    form = crud.update(db.note,note_id,deletable=False)
    if form.accepts(request.vars,session):
        session._flash = T('The sticky note was succesfully updated')
        form = None
    return dict(form=form)


@auth.requires_login()
def delete():
    note = None
    note_id = None

    if request.args:
        note = db(db.note.id==request.args(0)).select()

    if note:
        if note[0].user_id == auth.user.id:
            note_id = note[0].id
            db(db.note.id==note_id).delete()
            session._flash = T('The sticky note was succesfully deleted')
        else:
            session._flash = T('Access denied!')
    else:
         session._flash = T('Record not found!')

    redirect(URL(r=request,f='index'))

@auth.requires_login()
def delete_all():
    if db(db.note.user_id==auth.user.id).delete():
        session._flash = T('The sticky notes were succesfully deleted')
    else:
        session._flash = T('Nothing to delete!')

    redirect(URL(r=request,f='index'))


def user():
    """
    exposes:
    http://..../[app]/default/user/login 
    http://..../[app]/default/user/logout
    http://..../[app]/default/user/register
    http://..../[app]/default/user/profile
    http://..../[app]/default/user/retrieve_password
    http://..../[app]/default/user/change_password
    use @auth.requires_login()
        @auth.requires_membership('group name')
        @auth.requires_permission('read','table name',record_id)
    to decorate functions that need access control
    """
    if request.args[0] == 'login':
        if auth.user:
            redirect(URL(r=request,f='index'))
        response.view='user/login.html'
    elif request.args[0] == 'register':
        response.view='user/register.html'
    elif request.args[0] == 'retrieve_password':
        response.view='user/retrieve_password.html'
    return dict(form=auth())


def download():
    """
    allows downloading of uploaded files
    http://..../[app]/default/download/[filename]
    """
    return response.download(request,db)


def call():
    """
    exposes services. for example:
    http://..../[app]/default/call/jsonrpc
    decorate with @services.jsonrpc the functions to expose
    supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
    """
    return service()
